using UnityEngine;
using System.Collections;

public class BulletController : MonoBehaviour {
	public float Speed = 100.0f;	// speed of bullet
	public float MinDamage = 5.0f;
	public float MaxDamage = 10.0f;
	public float Duration = 1.0f; 	// life time
	public Transform Explosion;
	public int	Score = 0;

    public PlayerController sender;
    public int bulletIndex = 0 ;
    private float lifeTime = 0;

	// Use this for initialization
    //void Awake () {
    //    rigidbody.AddForce( transform.forward * Speed );
    //}
	
	// Update is called once per frame
	void Update () {
		lifeTime -= Time.deltaTime;

		if( lifeTime < 0.0f )
            MySpawner.Destroy(gameObject);
	}
	
	void OnCollisionEnter (Collision col)
	{
		// Ask collider to inflict damage
		col.collider.SendMessage( "InflictDamage", 
		                         Random.Range( MinDamage, MaxDamage ), 
		                         SendMessageOptions.DontRequireReceiver );
		
		// update score 
		if( Score > 0 && col.gameObject.tag != "Player" )
		{
			GameObject obj = GameObject.Find( "GameController" );
			obj.SendMessage( "UpdateScore", Score, SendMessageOptions.DontRequireReceiver );
		}

        //// Explode!
        //Instantiate( Explosion, transform.position, transform.rotation );
        //Destroy( gameObject );
        if (col.gameObject.tag == "Player")
        {
            sender.SendMessage("BulletCollision", bulletIndex);
        }
        else
        {
            Explode();
        }
	}

    void Init(BulletInitInfo info)
    {
        sender = info.sender;
        bulletIndex = info.index;
        lifeTime = this.Duration;
        rigidbody.velocity = Vector3.zero;
        rigidbody.AddForce(transform.forward * Speed);
    }

    void Explode()
    {
        // Explode!
        Instantiate(Explosion, transform.position, transform.rotation);
        MySpawner.Destroy(gameObject);
    }
}

public class BulletInitInfo
{
    public PlayerController sender;
    public int index;

    public BulletInitInfo(PlayerController s, int i)
    {
        sender = s;
        index = i;
    }
}
